import 'dart:convert';

import 'package:bruno/bruno.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart';
import 'package:pull_to_refresh_flutter3/pull_to_refresh_flutter3.dart';
import 'package:whale/helper/global/user/logic.dart';
import 'package:whale/helper/utils/util.dart';
import 'package:whale/pages/means/main/widgets/selection/index.dart';
import 'package:whale/pages/means/model/means_model.dart';

import '../../../helper/global/global.dart';
import '../model/area.dart';
import 'index.dart';

class MeansController extends GetxController
    with GetSingleTickerProviderStateMixin {
  MeansController();

  final state = MeansState();

  void requestForDocList() async {
    var reportType = state.reportType;
    if (reportType == null) {
      return;
    }
    var data = state.data[reportType];
    var res = await MeansApi.getDocList(
      pageIndex: state.pageIndex,
      type: reportType,
      keywords: state.inputCtrl.text,
      params: state.filterData,
    );
    if (res.isSuccess) {
      List? records = res.data['records'];
      var list = records?.map((e) => MeansModel.fromJson(e)).toList();
      if (state.pageIndex == 1) {
        data = list;
      } else {
        if (isZeroList(list)) {
          if (state.rc.isLoading) {
            state.rc.loadNoData();
          } else {
            state.rc.loadComplete();
          }
        }
        data?.addAll(list ?? []);
      }
      state.data[reportType] = data ?? [];
      update();
    }
    if (state.rc.isRefresh) {
      state.rc.refreshCompleted();
    }
  }

  void onRefresh() {
    state.pageIndex = 1;
    requestForDocList();
  }

  void onLoading() {
    state.pageIndex += 1;
    requestForDocList();
  }

  void selectionResults(SelectionResultModel res) {
    Get.log(res.toString());
    Map<String, String> args = state.filterData;

    if (res.key == '地区') {
      args['province'] = '';
      args['city'] = '';
      if (isZeroList(res.items)) {
        if (res.val == '全部') {
          args['province'] = '';
        } else {
          args['province'] = res.val ?? '';
        }
      } else {
        args['city'] = res.items!.map((e) => e.val ?? '').join(',');
      }
    } else if (res.key == '领域') {
      if (res.val == '全部') {
        args['industryType'] = '';
      } else {
        args['industryType'] = res.val ?? '';
      }
    } else if (res.key == '更多筛选') {
      args['startTime'] = '';
      args['endTime'] = '';
      args['riskLevel'] = '';

      res.items?.forEach((e2) {
        if (e2.key == '发布时间') {
          var dateVal = getDateVal(e2.val ?? '');
          if (dateVal.isEmpty) {
            args['startTime'] = '';
            args['endTime'] = '';
          } else {
            args['startTime'] = '${dateVal.first} 00:00:00';
            args['endTime'] = '${dateVal.last} 00:00:00';
          }
        } else if (e2.key == '风险等级') {
          args['riskLevel'] = e2.val ?? '';
        } else if (e2.key == '发布机构') {
        } else if (e2.key == '多个关键词组合查询') {
        } else {}
      });
    }
    state.filterData = args;
    onRefresh();
  }

  List<String> getDateVal(String data) {
    List<String> list = [];
    if (data == '全部') {
    } else if (data == '最近7天内') {
      var now = DateTime.now();
      var start = DateFormat.format(now, DateFormatType.ymd);
      var end = DateFormat.format(
          now.add(const Duration(days: -7)), DateFormatType.ymd);

      return [end, start];
    } else if (data == '最近一月') {
      var now = DateTime.now();
      var start = DateFormat.format(now, DateFormatType.ymd);
      var end = DateFormat.format(
          now.add(const Duration(days: -30)), DateFormatType.ymd);
      return [end, start];
    } else if (data == '最近一年') {
      var now = DateTime.now();
      var start = DateFormat.format(now, DateFormatType.ymd);
      var end = getEnd(start, 1);
      return [end, start];
    } else if (data == '最近三年') {
      var now = DateTime.now();
      var start = DateFormat.format(now, DateFormatType.ymd);
      var end = getEnd(start, 3);
      return [end, start];
    } else {
      return data.split(',').toList();
    }
    return list;
  }

  String getEnd(String start, int add) {
    var starts = start.split('-');
    var end = (int.parse(starts[0]) - add).toInt().toString();
    starts[0] = end;

    return starts.join('-');
  }

  /// 在 widget 内存中分配后立即调用。
  @override
  void onInit() {
    super.onInit();

    GlobalState().meansTabIndex.listen((p0) {
      state.tabCtrl.animateTo(p0);
    });

    state.reportType = '政策措施';
    state.rc = RefreshController();

    state.inputCtrl = TextEditingController();

    state.titles = ['政策措施', '招标采购', '审查制度', '违规案例'];
    state.tabCtrl = TabController(
      length: state.titles.length,
      vsync: this,
      initialIndex: GlobalState().meansTabIndex.value,
    )..addListener(() {
        if (state.tabCtrl.index != state.tabCtrl.previousIndex) {
          state.reportType = state.titles[state.tabCtrl.index];
          var data = state.data[state.reportType];
          if (data == null) {
            requestForDocList();
          } else {
            update();
          }
        }
      });
    setupSelectiondata();

    UserController().isLoginObs.listen((p0) {
      if (p0) {
        requestForDocList();
      } else {
        state.data[state.reportType!] = [];
        update();
      }
    });
  }

  void actionSearch() {
    if (state.inputCtrl.text == state.keywords) {
      return;
    }
    FocusScope.of(Get.context!).unfocus();
    state.keywords = state.inputCtrl.text;
    requestForDocList();
  }

  void loadAreaData() async {
    if (state.areaData != null) {
      return;
    }
    var val = await rootBundle.loadString('assets/jsons/area.json');
    var _json = json.decode(val);
    List list = _json['provinces'];
    state.areaData = list.map((e) => AreaModel.fromJson(e)).toList();
    List<SelectionModel> items = [
      SelectionModel(text: '全国', isShow: true, isMutiable: false, list: [
        SelectionModel(
          text: '全部',
          itemStyle: SelectionItemStyle.checkbox,
        )
      ]),
    ];
    items.addAll(state.areaData
            ?.map(
              (e) => SelectionModel(
                  text: e.provinceName,
                  itemStyle: SelectionItemStyle.checkbox,
                  style: SelectionStyle.column,
                  isMutiable: true,
                  list: e.citys
                      .map((e1) => SelectionModel(
                            text: e1,
                            itemStyle: SelectionItemStyle.checkbox,
                            isMutiable: true,
                          ))
                      .toList()),
            )
            .toList() ??
        []);
    state.selectionTitles.first.list = items;
  }

  Future<void> requestForFilters() async {
    if (state.fitlersList?.isNotEmpty != true) {
      var res = await MeansApi.postDocFilters();
      if (res.isSuccess) {
        state.fitlersList = res.data;
        List reports = res.data['reportTypeList'];
        state.titles = reports.map((e) => e['name'].toString()).toList();
        state.reportType = state.titles.first;
        List industrysData = res.data['poIndustryTypeList'];
        var industrys = industrysData.map((e) => e['name'].toString()).toList();
        industrys.insert(0, '全部');
        state.selectionTitles[1].list = industrys
            .asMap()
            .map((key, e) => MapEntry(
                  key,
                  SelectionModel(
                    text: e,
                    itemStyle: SelectionItemStyle.radio,
                    isMutiable: key != 0,
                    rowCount: 2,
                  ),
                ))
            .values
            .toList();
      }
    }
  }

  void setupSelectiondata() {
    state.selectionTitles = [
      SelectionModel(
          text: '地区', style: SelectionStyle.column, isMutiable: true, list: []),
      SelectionModel(
          text: '领域',
          style: SelectionStyle.wrap,
          isMutiable: true,
          rowCount: 2,
          list: []),
      SelectionModel(text: '更多筛选', style: SelectionStyle.column, list: [
        SelectionModel(
            title: '发布时间',
            text: '',
            isMutiable: false,
            style: SelectionStyle.wrap,
            rowCount: 3,
            tag: 1,
            relateTag: 2,
            list: ['全部', '最近7天内', '最近一月', '最近一年', '最近三年']
                .asMap()
                .map(
                  (key, value) => MapEntry(
                    key,
                    SelectionModel(
                      text: value,
                      rowCount: 3,
                      itemStyle: SelectionItemStyle.tag,
                    ),
                  ),
                )
                .values
                .toList()),
        SelectionModel(
          text: '',
          child: SizedBox(
            height: 10.r,
          ),
        ),
        SelectionModel(
            text: '',
            val: '',
            itemStyle: SelectionItemStyle.date,
            tag: 2,
            relateTag: 1),
        SelectionModel(
          text: '',
          child: SizedBox(
            height: 10.r,
          ),
        ),
        SelectionModel(text: '', title: '多个关键词组合查询', list: [
          SelectionModel(
            text: '',
            itemStyle: SelectionItemStyle.input,
          )
        ]),
        SelectionModel(
          text: '',
          child: SizedBox(
            height: 10.r,
          ),
        ),
        SelectionModel(text: '', title: '发布机构', list: [
          SelectionModel(
            text: '',
            itemStyle: SelectionItemStyle.input,
          )
        ]),
        SelectionModel(
          text: '',
          child: SizedBox(
            height: 10.r,
          ),
        ),
        SelectionModel(
            title: '风险等级',
            text: '',
            isMutiable: true,
            style: SelectionStyle.wrap,
            rowCount: 3,
            list: ['全部', '高风险', '中风险', '低风险', '暂无风险']
                .asMap()
                .map(
                  (key, value) => MapEntry(
                    key,
                    SelectionModel(
                      text: value,
                      isMutiable: key != 0,
                      rowCount: 3,
                      itemStyle: SelectionItemStyle.radio,
                    ),
                  ),
                )
                .values
                .toList()),
      ]),
    ];
  }

  /// 在 onInit() 之后调用 1 帧。这是进入的理想场所
  @override
  void onReady() async {
    super.onReady();

    await requestForFilters();
    requestForDocList();
    loadAreaData();
  }

  /// 在 [onDelete] 方法之前调用。
  @override
  void onClose() {
    super.onClose();
    state.tabCtrl.dispose();
    state.rc.dispose();
  }

  /// dispose 释放内存
  @override
  void dispose() {
    super.dispose();
  }
}
